<template>
  <div class="donation-page">
    <!-- 顶部暖色横幅 -->
    <section class="hero">
      <div class="hero-left">
        <h1>爱心捐赠 · 用一份善意温暖世界</h1>
        <p>每一笔捐赠，都是光。感谢你的关怀与支持。</p>
        <div class="hero-stats">
          <div class="stat">
            <div class="stat-num">¥ {{ totalAmount.toLocaleString() }}</div>
            <div class="stat-label">累计捐赠金额</div>
          </div>
          <div class="stat">
            <div class="stat-num">{{ totalCount }}</div>
            <div class="stat-label">捐赠笔数</div>
          </div>
        </div>
      </div>
      <div class="hero-right">
        <svg viewBox="0 0 200 200" class="hero-illustration" aria-hidden="true">
          <defs>
            <linearGradient id="g1" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0%" stop-color="#FF8A80"/>
              <stop offset="100%" stop-color="#FF5252"/>
            </linearGradient>
            <linearGradient id="g2" x1="1" x2="0" y1="0" y2="1">
              <stop offset="0%" stop-color="#FFD180"/>
              <stop offset="100%" stop-color="#FF9E80"/>
            </linearGradient>
          </defs>
          <path d="M100 170 C 30 120, 10 90, 30 60 C 50 30, 85 40, 100 60 C 115 40, 150 30, 170 60 C 190 90, 170 120, 100 170 Z"
                fill="url(#g1)"/>
          <circle cx="150" cy="50" r="10" fill="url(#g2)" opacity="0.9"/>
          <circle cx="60" cy="40" r="6" fill="white" opacity="0.65"/>
        </svg>
      </div>
    </section>

    <!-- 主体：左内容（搜索+表格），右侧统计卡片 -->
    <section class="content">
      <div class="left">
        <!-- 搜索 -->
        <el-card class="search-card">
          <el-form :inline="true" :model="query" ref="searchFormRef">
            <el-form-item label="受助人">
              <el-input v-model="query.recipient" placeholder="请输入受助人" clearable />
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="query.order_no" placeholder="订单号" clearable />
            </el-form-item>
<!--            &lt;!&ndash; 捐赠时间范围（使用 ISO 格式带 T） &ndash;&gt;-->
<!--            <el-form-item label="捐赠时间">-->
<!--              <el-date-picker-->
<!--                  v-model="query.donateTimeRange"-->
<!--                  type="datetimerange"-->
<!--                  range-separator="至"-->
<!--                  start-placeholder="开始时间"-->
<!--                  end-placeholder="结束时间"-->
<!--                  value-format="YYYY-MM-DDTHH:mm:ss"-->
<!--                  style="width: 320px"-->
<!--                  clearable-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
              <el-button type="success" @click="openAdd">新增捐赠</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 表格 -->
        <el-card>
          <el-table :data="table" v-loading="loading" style="width:100%">
            <el-table-column prop="order_no" label="订单号" min-width="120" />
            <el-table-column prop="recipient" label="受助人" min-width="120" />
            <el-table-column prop="amount" label="金额(¥)" width="120">
              <template #default="{ row }">¥ {{ Number(row.amount || 0).toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="捐赠时间" min-width="160">
              <template #default="{ row }">{{ toDisplay(row.donate_time) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="remove(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              class="pagination"
              v-model:current-page="query.current"
              v-model:page-size="query.limit"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
          />
        </el-card>
      </div>

      <!-- 右侧爱心统计卡 -->
      <div class="right">
        <el-card class="stat-card">
          <div class="stat-title">今日亮点</div>
          <div class="stat-block">
            <div class="stat-row">
              <span>今日新增金额</span>
              <b>¥ {{ todayAmount.toFixed(2) }}</b>
            </div>
            <div class="stat-row">
              <span>今日捐赠笔数</span>
              <b>{{ todayCount }}</b>
            </div>
          </div>
          <div class="divider"></div>
          <div class="recipient-list">
            <div class="list-title">近期受助人</div>
            <ul>
              <li v-for="(r, i) in recentRecipients" :key="i">
                <span class="avatar">{{ r.name?.[0]?.toUpperCase() || '爱' }}</span>
                <div class="info">
                  <div class="name">{{ r.name }}</div>
                  <div class="amt">¥ {{ r.amount.toFixed(2) }}</div>
                </div>
              </li>
              <li v-if="recentRecipients.length === 0" class="empty">暂无数据</li>
            </ul>
          </div>
        </el-card>
      </div>
    </section>

    <!-- 弹窗：新增/编辑 -->
    <el-dialog v-model="dialog.visible" :title="dialog.mode === 'add' ? '新增捐赠' : '编辑捐赠'" width="520px">
      <el-form :model="form" label-width="90px" ref="formRef" :rules="formRules">
        <el-form-item label="订单号" required prop="order_no">
          <el-input v-model="form.order_no" placeholder="如：ORDER2025xxx" />
        </el-form-item>
        <el-form-item label="金额(¥)" required prop="amount">
          <el-input
              v-model.number="form.amount"
              type="number"
              placeholder="请输入金额"
              step="0.01"
              min="0.01"
          />
        </el-form-item>
        <el-form-item label="受助人" required prop="recipient">
          <el-input v-model="form.recipient" placeholder="请输入受助人" />
        </el-form-item>
        <el-form-item label="捐赠时间" required prop="donate_time">
          <el-date-picker
              v-model="form.donate_time"
              type="datetime"
              placeholder="选择日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible=false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/api/donation_api.js';

/** 小工具：保证/展示时间格式 */
const pad2 = (n) => String(n).padStart(2, '0');
const nowIsoLocal = () => {
  const d = new Date();
  // 用本地时间拼 yyyy-MM-ddTHH:mm:ss （不带时区）
  const y = d.getFullYear();
  const m = pad2(d.getMonth() + 1);
  const day = pad2(d.getDate());
  const h = pad2(d.getHours());
  const mi = pad2(d.getMinutes());
  const s = pad2(d.getSeconds());
  return `${y}-${m}-${day}T${h}:${mi}:${s}`;
};
const toDisplay = (val) => (val ? String(val).replace('T', ' ') : '');

/* ---------------- state ---------------- */
const loading = ref(false);
const table = ref([]);
const total = ref(0);

const query = ref({
  current: 1,
  limit: 10,
  recipient: '',
  order_no: '',
  donateTimeRange: [] // [startIsoT, endIsoT]
});

const searchFormRef = ref(null);

const totalAmount = computed(() =>
    table.value.reduce((sum, item) => sum + Number(item.amount || 0), 0)
);
const totalCount = computed(() => table.value.length);

const todayAmount = computed(() => {
  const todayStr = new Date().toISOString().slice(0, 10);
  return table.value
      .filter(item => String(item.donate_time || '').slice(0, 10) === todayStr)
      .reduce((sum, item) => sum + Number(item.amount || 0), 0);
});
const todayCount = computed(() => {
  const todayStr = new Date().toISOString().slice(0, 10);
  return table.value.filter(item => String(item.donate_time || '').slice(0, 10) === todayStr).length;
});
const recentRecipients = computed(() => {
  const recipientMap = new Map();
  table.value.forEach(item => {
    const name = item.recipient || '匿名';
    const amount = Number(item.amount || 0);
    recipientMap.set(name, (recipientMap.get(name) || 0) + amount);
  });
  return Array.from(recipientMap.entries())
      .map(([name, amount]) => ({ name, amount }))
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 6);
});

/* ------------- dialog / form ------------ */
const dialog = ref({ visible: false, mode: 'add' });
const formRef = ref(null);
const form = ref({
  donation_id: null,
  order_no: '',
  amount: null,
  recipient: '',
  donate_time: nowIsoLocal()        // ★ 默认就是带 T 的 ISO 本地时间
});

const formRules = ref({
  order_no: [
    { required: true, message: '请输入订单号', trigger: 'blur' },
    { min: 5, max: 30, message: '订单号长度在 5-30 个字符之间', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入捐赠金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于 0', trigger: 'blur' }
  ],
  recipient: [
    { required: true, message: '请输入受助人', trigger: 'blur' },
    { min: 1, max: 50, message: '受助人名称长度在 1-50 个字符之间', trigger: 'blur' }
  ],
  donate_time: [
    { required: true, message: '请选择捐赠时间', trigger: 'change' }
  ]
});

/* ---------------- load & helpers ---------------- */
const cleanEmpty = (obj) => {
  const result = {};
  Object.entries(obj).forEach(([k, v]) => {
    if (v !== '' && v !== null && v !== undefined) result[k] = v;
  });
  return result;
};

const load = async () => {
  loading.value = true;
  try {
    const queryParams = {
      current: query.value.current,
      limit: query.value.limit,
      recipient: query.value.recipient,
      order_no: query.value.order_no,
      donateStartTime: query.value.donateTimeRange?.[0] || '',  // ★ 已经是 T 格式
      donateEndTime: query.value.donateTimeRange?.[1] || ''
    };
    const res = await api.page(cleanEmpty(queryParams));

    const root = res?.data ?? res ?? {};
    const box = root.data ?? root;

    let list =
        (Array.isArray(box) ? box : null) ||
        box.data || box.list || box.records || box.rows || [];

    if (!Array.isArray(list) && Array.isArray(box?.data?.data)) {
      list = box.data.data;
    }

    let totalCount =
        root.total ?? root.count ??
        box.total ?? box.count ?? box?.data?.total ?? box?.data?.count ??
        (Array.isArray(list) ? list.length : 0);

    table.value = (list || []).map(item => ({
      donation_id: item.donation_id ?? item.donationId ?? item.id,
      order_no: item.order_no ?? item.orderNo ?? '',
      recipient: item.recipient ?? '匿名',
      amount: item.amount ?? 0,
      donate_time: item.donate_time ?? item.donateTime ?? '' // 保持后端原样（可能带 T/不带 T）
    }));

    total.value = Number(totalCount) || 0;
  } catch (error) {
    console.error('加载失败:', error);
    ElMessage.error(`加载失败: ${error.message || '网络异常'}`);
    table.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/* ---------------- actions ---------------- */
const search = () => {
  query.value.current = 1;
  load();
};

const resetQuery = () => {
  query.value = {
    current: 1,
    limit: 10,
    recipient: '',
    order_no: '',
    donateTimeRange: []
  };
  searchFormRef.value?.resetFields?.();
  load();
};

const handlePageChange = (page) => {
  query.value.current = page;
  load();
};

const handleSizeChange = (size) => {
  query.value.limit = size;
  query.value.current = 1;
  load();
};

const openAdd = () => {
  dialog.value = { visible: true, mode: 'add' };
  form.value = {
    donation_id: null,
    order_no: '',
    amount: null,
    recipient: '',
    donate_time: nowIsoLocal()   // ★ 带 T 的默认值
  };
  formRef.value?.clearValidate?.();
};

const openEdit = (row) => {
  dialog.value = { visible: true, mode: 'edit' };
  // 兼容：如果后端返回了空格分隔，这里转成 T，确保回填到 date-picker 正常
  const raw = row.donate_time || '';
  const isoT = raw.includes('T') ? raw : raw.replace(' ', 'T');
  form.value = {
    donation_id: row.donation_id,
    order_no: row.order_no,
    amount: Number(row.amount),
    recipient: row.recipient,
    donate_time: isoT
  };
  formRef.value?.clearValidate?.();
};

const submit = async () => {
  // 先校验
  try {
    await formRef.value?.validate();
  } catch (error) {
    return; // ElementPlus 已提示
  }

  try {
    const submitData = {
      order_no: form.value.order_no,
      amount: form.value.amount,
      recipient: form.value.recipient,
      donate_time: form.value.donate_time // ★ 已是 YYYY-MM-DDTHH:mm:ss
    };
    if (dialog.value.mode === 'edit') submitData.donation_id = form.value.donation_id;

    if (dialog.value.mode === 'add') {
      await api.add(submitData);
      ElMessage.success('新增成功');
    } else {
      await api.edit(submitData);
      ElMessage.success('编辑成功');
    }
    dialog.value.visible = false;
    load();
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error(`操作失败: ${error.message || '服务器异常'}`);
  }
};

const remove = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除订单号为【${row.order_no}】的捐赠记录吗？`,
        '确认删除',
        { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' }
    );
    await api.del(row.donation_id);
    ElMessage.success('删除成功');
    load();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(`删除失败: ${error.message || '服务器异常'}`);
    }
  }
};

onMounted(load);
</script>

<style scoped>
.donation-page { padding: 16px; }

/* 顶部横幅 */
.hero {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr;
  gap: 16px;
  padding: 24px 20px;
  border-radius: 16px;
  background: linear-gradient(135deg, #fff3f1 0%, #fffbf7 100%);
  border: 1px solid #ffe0dc;
  box-shadow: 0 10px 30px rgba(255, 160, 160, 0.12);
  margin-bottom: 18px;
}
.hero-left h1 { margin: 0 0 8px; font-size: 22px; color: #d84315; font-weight: 700; }
.hero-left p { margin: 0 0 14px; color: #8d6e63; }
.hero-stats { display: flex; gap: 18px; }
.stat { background: #fff; padding: 10px 14px; border-radius: 12px; border: 1px solid #ffe3de; }
.stat-num { font-size: 20px; font-weight: 700; color: #e53935; }
.stat-label { color: #8d6e63; font-size: 12px; }
.hero-right { display: flex; align-items: center; justify-content: center; }
.hero-illustration { width: 160px; height: 160px; }

/* 主体布局 */
.content {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 300px;
  gap: 16px;
}
.left .search-card { margin-bottom: 12px; }
.pagination { margin-top: 14px; justify-content: center; }

/* 右侧卡片 */
.stat-card { position: sticky; top: 12px; }
.stat-title { font-weight: 700; color: #d84315; margin-bottom: 6px; }
.stat-block { background: #fff7f4; border: 1px solid #ffe2d9; border-radius: 10px; padding: 10px; }
.stat-row { display: flex; justify-content: space-between; padding: 6px 0; color: #6d4c41; }
.divider { height: 1px; background: #f5d3cc; margin: 12px 0; }

.recipient-list .list-title { font-weight: 600; color: #8d6e63; margin-bottom: 8px; }
.recipient-list ul { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }
.recipient-list li { display: flex; align-items: center; gap: 10px; padding: 8px; border: 1px solid #ffe3de; border-radius: 10px; background: #fff; }
.recipient-list .avatar {
  width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center;
  background: #ffccbc; color: #bf360c; font-weight: 700;
}
.recipient-list .info .name { font-weight: 600; color: #6d4c41; }
.recipient-list .info .amt { color: #8d6e63; font-size: 12px; }
.recipient-list .empty { color: #9e9e9e; justify-content: center; }

/* 响应式调整 */
@media (max-width: 1024px) {
  .hero { grid-template-columns: 1fr; }
  .content { grid-template-columns: 1fr; }
}
</style>
